import rest_framework
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.http import JsonResponse, HttpResponseBadRequest
from django.contrib.auth import authenticate, login, logout
from django.views.decorators.csrf import csrf_exempt
from rest_framework.authtoken.models import Token
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from utils.response import APIResponse
import json
import os
from django.conf import settings
from django.core.files.storage import default_storage

@csrf_exempt
@api_view(['GET', 'PUT'])
@permission_classes([IsAuthenticated])
def user_info(request):
    if request.method == 'GET':
        try:
            user = request.user
            return APIResponse.rest_success(message="成功获取用户信息",data={
                'id': user.id,
                'username': user.username,
                'email': user.email,
                'first_name': user.first_name,  # 头像URL
                'last_name': user.last_name,
                'is_staff': user.is_staff,
                'is_active': user.is_active,
                'is_superuser': user.is_superuser,
                'date_joined': user.date_joined.strftime('%Y-%m-%d %H:%M:%S'),
                'last_login': user.last_login.strftime('%Y-%m-%d %H:%M:%S') if user.last_login else None
            })
        except Exception as e:
            return APIResponse.rest_error(message=str(e), status=500)

    elif request.method == 'PUT':
        try:
            user = request.user
            data = json.loads(request.body)

            if 'email' in data:
                if User.objects.filter(email=data['email']).exclude(id=user.id).exists():
                    return APIResponse.rest_error(message='邮箱已被使用', status=400)
                user.email = data['email']
            if 'first_name' in data:  # 更新头像URL
                user.first_name = data['first_name']
            if 'last_name' in data:
                user.last_name = data['last_name']

            user.full_clean()
            user.save()
            return APIResponse.rest_success(message='用户信息更新成功')
        except ValidationError as e:
            return APIResponse.rest_error(message=str(e), status=400)
        except Exception as e:
            return APIResponse.rest_error(message=str(e), status=500)


# 新增文件上传视图
@csrf_exempt
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def upload_avatar(request):
    if request.method == 'POST':
        try:
            if 'file' not in request.FILES:
                return APIResponse.rest_error(message='未提供文件', status=400)

            file_obj = request.FILES['file']
            # 确保上传目录存在
            upload_dir = os.path.join(settings.MEDIA_ROOT, 'avatars')
            os.makedirs(upload_dir, exist_ok=True)

            # 生成文件名并保存
            file_name = f"{request.user.username}_{file_obj.name}"
            file_path = os.path.join('avatars', file_name)
            default_storage.save(file_path, file_obj)

            # 构建完整的URL
            avatar_url = f"{settings.MEDIA_URL}{file_path}"

            # 更新用户的first_name字段
            request.user.first_name = avatar_url
            request.user.save()

            return APIResponse.rest_success(data={'url': avatar_url})
        except Exception as e:
            return APIResponse.rest_error(message=str(e), status=500)
    return HttpResponseBadRequest("此 URL 只接受 POST 请求")


@csrf_exempt
@api_view(['POST'])
@permission_classes([rest_framework.permissions.AllowAny])
def user_login(request):
    try:
        data = json.loads(request.body)
        user = authenticate(request, username=data['username'], password=data['password'])
        if user is not None:
            login(request, user)
            token, created = Token.objects.get_or_create(user=user)
            return APIResponse.rest_success(message='登录成功',data={'token': token.key})
        else:
            return APIResponse.rest_error(message='无效的用户名或密码', status=401)
    except Exception as e:
        return APIResponse.rest_error(message=str(e), status=400)


@csrf_exempt
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def user_logout(request):
    try:
        # 删除用户的token
        request.user.auth_token.delete()
        # 登出用户
        logout(request)
        return APIResponse.rest_success(message='退出成功')
    except Exception as e:
        return APIResponse.rest_error(message=str(e), status=500)


@csrf_exempt
@api_view(['POST'])
@permission_classes([rest_framework.permissions.AllowAny])
def user_register(request):
    try:
        data = json.loads(request.body)
        username = data.get('username')
        password = data.get('password')
        email = data.get('email')

        if not all([username, password, email]):
            return APIResponse.rest_error(message='所有字段都是必填的', status=400)

        if User.objects.filter(username=username).exists():
            return APIResponse.rest_error(message='用户名已存在', status=400)

        if User.objects.filter(email=email).exists():
            return APIResponse.rest_error(message='邮箱已被注册', status=400)

        user = User.objects.create_user(username=username, email=email, password=password)
        token, created = Token.objects.get_or_create(user=user)

        return APIResponse.rest_success(data={
            'id': user.id,
            'username': user.username,
            'email': user.email,
            'token': token.key
        }, message='注册成功', status=201)
    except Exception as e:
        return APIResponse.rest_error(message=str(e), status=500)


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def change_password(request):
    try:
        data = json.loads(request.body)
        old_password = data.get('old_password')
        new_password = data.get('new_password')

        if not all([old_password, new_password]):
            return APIResponse.rest_error(message='所有字段都是必填的', status=400)

        user = request.user
        if not user.check_password(old_password):
            return APIResponse.rest_error(message='原密码错误', status=400)

        user.set_password(new_password)
        user.save()

        # 删除旧token
        Token.objects.filter(user=user).delete()
        # 创建新token
        token = Token.objects.create(user=user)

        return APIResponse.rest_success(data={'access': token.key}, message='密码修改成功')
    except Exception as e:
        return APIResponse.rest_error(message=str(e), status=500)


@api_view(['PUT'])
@permission_classes([IsAuthenticated])
def update_user_info(request):
    try:
        user = request.user
        data = json.loads(request.body)

        if 'email' in data:
            if User.objects.filter(email=data['email']).exclude(id=user.id).exists():
                return APIResponse.rest_error(message='邮箱已被使用', status=400)
            user.email = data['email']

        if 'password' in data:
            user.set_password(data['password'])

        user.save()
        return APIResponse.rest_success(message='更新成功')
    except Exception as e:
        return APIResponse.rest_error(message=str(e), status=500)